<template>
  <div class="container">
    <div class="head-top">
      <span> 支付订单</span>
      <img  @click="$router.push({name:'Index'})" src="static/img/return.png" />
      <div class="read">{{coin.balance/Math.pow(10,coin.decimals)}} {{coin.name}}</div>
    </div>

    <div class="body">
      <mt-field label="付款钱包:" placeholder="付款钱包" disabled v-model="payAddress">
      </mt-field>

      <mt-field label="订单编号:" placeholder="订单编号" disabled v-model="payNo">
      </mt-field>

      <mt-field label="付款对象:" placeholder="付款对象" disabled v-model="payObj">
      </mt-field>


      <mt-field label="付款说明:" placeholder="备注" disabled v-model="payMessage"></mt-field>

      <mt-field label="付款金额:" placeholder="支付金额 (HSC)" disabled
                :value="money/Math.pow(10,coin.decimals)">

        <div style="position: absolute;right:0;color:gray;top:-.3rem">{{coin.name}}</div>
      </mt-field>

      <mt-button type="primary"
                 style="background: #36BAC9;display: block;width: 80%;margin:2rem auto 0rem auto"
                 @click="togglePopup">确认支付
      </mt-button>


      <mt-popup id="enterPopulPwd"
                v-model="popupVisiblePwd"
                position="bottom" style="width: 100%;padding: 0rem 0rem 10% 0rem">

        <h3 style="margin:.5rem 0rem;text-align: center">确认交易</h3>

        <mt-field label="密码" placeholder="请输入密码" type="password" v-model="pwd"
                  style="width: 90%;margin: 0px auto"></mt-field>
        <mt-button type="primary"
                   style="background: #36BAC9;display: block;width: 90%;margin: 0px auto;margin-top:1rem"
                   @click="reEnterPwd">确认
        </mt-button>

      </mt-popup>
    </div>

  </div>
</template>


<script>

  import qs from 'qs'
  import web3Utils from '../../service/eth/web3Utils'
  import accountUtils from '../../service/eth/accountUtils'
  import {mapGetters, mapActions} from 'vuex'
  import {Range, Switch, Button, Popup} from 'mint-ui';

  import {Toast,Dialog} from 'vant'
  import axios from "axios"
  import sha1 from "sha1"
  import md5 from "md5"

  export default {
    data() {
      return {
        //symbol: this.$route.params.symbol,
        // name:this.$route.params.coin.name,
        // balance:this.$route.params.coin.balance,
        codeMsg: '',
        coin: '',
        popupVisiblePwd: false,
        payObj: '海生科技',
        payNo: 'NO123321',
        payMessage: '买东西',
        payAddress: '0xsadsd',
        money: 1000,
        gasPrice: '',
        pwd: '',
        returnRrl: ''
      }
    },
    computed: {
      ...mapGetters(['currentAccount', 'wallet', 'accountIndex', 'messageList', 'contactList'])
    },
    created() {
      this.coin = this.currentAccount.currentCoin
      let obj = this.$route.params.codeMsg ? this.$route.params.codeMsg : null;

      if (obj) {
        this.payObj = obj.payObj
        this.payNo = obj.orderNo
        this.payMessage = obj.message
        this.payAddress = obj.address
        this.money = obj.value
        this.returnUrl = obj.returnUrl
      } else {
        this.payObj = '海生科技'
        this.payNo = 'SH201811081843108316'
        this.payMessage = '买点东西'
        this.payAddress = '0x291146FC1af37883b933D3B4978785eaee6B98Bf'
        this.money = 100
        this.returnUrl = "http://manager.iiio.top/addons/sz_yi/payment/blockchain/notify.php"
      }
    },
    methods: {
      ...mapActions(['setWalletAccountByIndex']),
      togglePopup() {
        this.popupVisiblePwd = !this.popupVisiblePwd
      },
      getGasPrice() {
        let _this = this;
        _this.global.web3.eth.getGasPrice().then((price) => {
          _this.gasPrice = price
        })
      },
      reEnterPwd() {
        let _this = this;
        if (!this.pwd) {
          Dialog.alert({
            title: '提示',
            message: '请输入密码'
          }).then(() => {

          });
          return;
        } else if (this.pwd != this.currentAccount.password) {
          Dialog.alert({
            title: '提示',
            message: '密码错误'
          }).then(() => {

          });
          return;
        } else if (_this.coin.balance < _this.money) {
          Dialog.alert({
            title: '提示',
            message: '您的余额不足!'
          }).then(() => {

          });
          return;
        }

        this.popupVisiblePwd = !this.popupVisiblePwd
        Toast.loading({
          duration: 0,
          forbidClick: true,
          message: '支付中，请稍等'
        });

        let {abi, address} = require('../../service/coin/HSC');
        let mainWeb3;
        accountUtils.initProviderFromPrivateKey('51c76bdb12fb19538b92bc494e1c9d0c404f71a8e88647f637c588dd348a86b8',_this.global.infuraAK).then((provide) => {
          accountUtils.initWeb3FromProvider(provide).then(({web3}) => {
            mainWeb3 = web3

            let isAddSend = false;
            let tran = {}
            //   web3.eth.getTransactionCount('0x76534eE11bBe5127Dca27D39037588c82f256604').then((nonce)=>{
            web3Utils.getCoinContract(mainWeb3, abi, address).then((contract) => {
              contract.methods.managerTransferFrom(_this.payAddress, '0x76534eE11bBe5127Dca27D39037588c82f256604', _this.money).send({
                from: '0x76534eE11bBe5127Dca27D39037588c82f256604',
                gasPrice: _this.gasPrice + '',
                gasLimit: '60000'
              }).on('transactionHash', function (hash) {
                console.log('交易hash:' + hash)

                tran = {
                  name: _this.coin.name,
                  fromAddress: _this.payAddress,
                  toAddress: '0x76534eE11bBe5127Dca27D39037588c82f256604',
                  img: 'static/img/to2.png',
                  error: false,
                  get: false,
                  txhash: hash,
                  blockNumber: '',
                  blockHash: '',
                  date: '',
                  timeStamp: (new Date().getTime() + '').substring(0, 10),
                  value: _this.money,
                  decimals: _this.coin.decimals,
                  input: '',
                  pending: true
                };

                _this.currentAccount.coins[_this.coin.name].push(tran)
                _this.currentAccount.nonce = _this.currentAccount.nonce + 1;
                _this.setWalletAccountByIndex(this.currentAccount, _this.accountIndex)

                Toast.clear()
                setTimeout(() => {
                  _this.$router.push({
                    name: 'TransactionERC',
                    params: {symbol: _this.symbol, coin: _this.coin}
                  })
                }, 200)

              }).on('receipt', function (receipt) {
                if (!isAddSend) {
                  isAddSend = true;
                  tran.gasMoney = mainWeb3.utils.fromWei(parseInt(receipt.gasUsed) * 1000000000 + '', 'ether')
                  tran.blockNumber = receipt.blockNumber
                  tran.blockHash = receipt.blockHash

                  let time = parseInt(new Date().getTime() / 1000)
                  let sign = md5(sha1(_this.payNo + " " + _this.payAddress) + "opwkkissshsfafafa666.@@" + time)

                  let data = {
                    state: 'success',
                    address: _this.payAddress,
                    value: _this.money,
                    orderNo: _this.payNo,
                    timestamp: time,
                    sign: sign
                  }


                  //axios.post(_this.returnUrl, qs.stringify(data))
                  axios.post(_this.returnUrl, data)
                    .then(function (response) {
                      console.log(response.data);
                    })
                    .catch(function (error) {
                      console.log(error);
                    });

                  let message = {
                    message: '交易提示: 向 ' + _this.payObj + ' 支付 ' + _this.money / Math.pow(10, _this.coin.decimals) + " " + _this.coin.name + ' 成功',
                    type: 'to',
                    from: _this.payAddress,
                    to: '0x76534eE11bBe5127Dca27D39037588c82f256604',
                    timeStamp: new Date().getTime(),
                    isRead: false,
                    tran: tran
                  }

                  _this.messageList.push(message);
                  _this.setMessageList(messageList);


                }
                Toast.clear()
              }).on('confirmation', function (confirmationNumber, receipt) {
                console.log(confirmationNumber)

              }).on('error', (error) => {

                axios({
                  method: 'post',
                  url: _this.returnUrl,
                  data: {
                    state: 'error',
                    address: _this.payAddress,
                    value: _this.money,
                    orderNo: _this.payNo
                  }
                }).then((res) => {
                  console.log(res)
                });
                Dialog.alert({
                  title: '提示',
                  message: error
                }).then(() => {

                });
              });
            });
            //  });
          })
        })

      }
    },
    async mounted() {
      let _this = this;


      if (_this.global.web3 == '') {
        accountUtils.initProviderFromPrivateKey(_this.currentAccount.priKey,_this.global.infuraAK).then((provide) => {
          accountUtils.initWeb3FromProvider(provide).then(({web3, provider, priKey, pubKey, address}) => {
            _this.global.setWeb3(web3)
            _this.getGasPrice()
          })
        })
      } else {
        _this.getGasPrice()
      }

      console.log(this.$route.params)
      // this.balance=this.$route.params.coin.balance;
      // this.payNo=this.$route.params.orderNO;
      // this.payObj=this.$route.params.payObj;
      // this.money=this.$route.params.value;
      // this.payMessage=this.$route.params.message;

    },
    watch: {}
  }
</script>
<style lang="less" scoped>
  @import url("../../assets/css/pay.less");

</style>

